/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年5月5日 上午9:56:29
 */
package com.lenovo.lmrp.server.assigntracer.scheduler;

import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.lenovo.lmrp.api.constant.SendType;
import com.lenovo.lmrp.server.assigntracer.util.pusher.GeTuiTemplete;
import com.lenovo.lmrp.server.assigntracer.util.pusher.PushParameter;
import com.lenovo.lmrp.server.assigntracer.util.pusher.SMSRequestImpl;
import com.lenovo.lmrp.server.assigntracer.util.pusher.SMSResponseImpl;
import com.lenovo.sdc.framework.scheduler.ACommonTask;
import com.lenovo.sdc.framework.scheduler.Schedule;
import com.lenovo.sdc.framework.sns.EMail;
import com.lenovo.sdc.framework.sns.MailSender;
import com.lenovo.sdc.framework.sns.SMSHttpClient;
import com.lenovo.sdc.framework.sns.ASMSRequest.ContentType;
import com.lenovo.sdc.framework.util.AttributeBean;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author zhangzheng
 *
 */
public class RetryPushMessageTask extends ACommonTask {

    private static Logger logger = LoggerFactory.getLogger(RetryPushMessageTask.class);

    private String taskID;
    private Schedule schedule;
    private String itsmCode;
    private PushParameter pushParameter;
    private AttributeBean attributes;
    private int retryInterval;
    private int retryCount;
    private String proxyHost;
    private String proxyPort;
    /**
     * 
     */
    public RetryPushMessageTask(PushParameter pushParameter, AttributeBean attributes) {
        this.pushParameter = pushParameter;
        this.attributes = attributes;
        this.itsmCode = pushParameter.getItsmcode();
        this.taskID = itsmCode + ":retrypushmessagetask:" + pushParameter.getSendType().name() + ":"
                      + System.currentTimeMillis();
        this.proxyHost = attributes.getAttribute("http.proxy.ip", "");
        this.proxyPort = attributes.getAttribute("http.proxy.port", "");
        
        //重试时间间隔和重试次数
        retryInterval = attributes.getAttribute("pushmessage.retry.interval", 15);
        retryCount = attributes.getAttribute("pushmessage.retry.count", 2);
        //计算定时任务结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, retryCount * retryInterval);

        Date taskEndDate = calendar.getTime();
        schedule = new Schedule(retryInterval);
        schedule.setEndTime(taskEndDate);
    }

    /* (non-Javadoc)
     * @see com.lenovo.sdc.framework.scheduler.ACommonTask#getID()
     */
    @Override
    public String getID() {
        return taskID;
    }

    /* (non-Javadoc)
     * @see com.lenovo.sdc.framework.scheduler.ACommonTask#getSchedule()
     */
    @Override
    public Schedule getSchedule() {
        return schedule;
    }

    /* (non-Javadoc)
     * @see com.lenovo.sdc.framework.scheduler.ACommonTask#execute()
     */
    @Override
    public void execute() throws Exception {
        try {
            SendType sendType = this.pushParameter.getSendType();
            switch (sendType) {
                case GETUI:
                    this.retryGt();
                    return;
                case SMS:
                    this.retrySMS();
                    return;
                case EMAIL:
                    this.retryEmail();
                    return;
                case WEICHART:
                    return;
                default:
                    logger.debug("ignore {}", sendType.name());
                    return;
            }
        }
        catch (Exception exp) {
            throw new TraceableException(ErrorCode.COMM_ERROR, "retry pushmessage task[" + this.taskID + "] failed.",exp);
        }

    }
    //个推
    private void retryGt() {
        IGtPush gtPush = new IGtPush(attributes.getAttribute("geTui.host", "http://sdk.open.api.igexin.com/serviceex"),
            attributes.getAttribute("geTui.appKey", "s50xUUFOK28NGCSpm4nVv2"),
            attributes.getAttribute("geTui.master", "6qdW3B9vet9adpIoHTIdz7"));
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(attributes.getAttribute("geTui.appId", "q5mUcjkb8I8HlbDSmpBoh2"));
        template.setAppkey(attributes.getAttribute("geTui.appKey", "s50xUUFOK28NGCSpm4nVv2"));

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);

        String content = pushParameter.getContent();
        String title = pushParameter.getTitle();
        String desc = pushParameter.getDesc();
        int getuiType = pushParameter.getGetuiType();
        GeTuiTemplete geTuiTemplete = new GeTuiTemplete();
        geTuiTemplete.setContent(content);
        geTuiTemplete.setTitle(title);
        geTuiTemplete.setDesc(desc);
        geTuiTemplete.setType(getuiType);
        try {
            template.setTransmissionContent(JSONHelper.toJSON(geTuiTemplete));
        } catch (Exception e) {
            throw new TraceableException(ErrorCode.COMM_PARSE_FAILED, e);
        }

        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(Long.parseLong(attributes.getAttribute("geTui.message.offLineTime", "86400000")));
        message.setData(template);
        message.setPushNetWorkType(0); // 可选。判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
        Target target = new Target();
        target.setAppId(attributes.getAttribute("geTui.appId", "q5mUcjkb8I8HlbDSmpBoh2"));
        target.setClientId(pushParameter.getcId());
        IPushResult ret = gtPush.pushMessageToSingle(message, target);
        if ("ok".equals(ret.getResponse().get("result"))) {
            logger.debug("retry pushmessage task[{}] successed.",this.taskID);
            this._stop();
        }
    }
    //短信
    private void retrySMS() {
        String proxy = null;
        if (CommonUtil.nonNullAndEmpty(proxyHost) && CommonUtil.nonNullAndEmpty(proxyPort)) {
            proxy = proxyHost + ":" + proxyPort;
        }
        SMSHttpClient smsHttpClient = new SMSHttpClient(attributes.getAttribute("short.host", ""), proxy);
        SMSRequestImpl smsRequestImpl = new SMSRequestImpl(ContentType.XML,
            attributes.getAttribute("short.username", "gaoyi4"),
            attributes.getAttribute("short.password", "gaoyi4"), pushParameter.getMobile(),
            pushParameter.getContent());
        SMSResponseImpl smsResponseImpl = new SMSResponseImpl();
        smsHttpClient.sendSMS(smsRequestImpl, smsResponseImpl);
        if (smsResponseImpl.getStuats() == 0) {
            smsResponseImpl = smsResponseImpl.getBody();
            if ("调用成功，短信已发送".equals(smsResponseImpl.getStateMessage())
                && "00".equals(smsResponseImpl.getResultCode())) {
                logger.debug("retry pushmessage task[{}] successed.",this.taskID);
                this._stop();
            }
        }
    }
    //邮件
    private void retryEmail() throws Exception {
        
        MailSender mailSender = new MailSender(attributes.getAttribute("email.smtpHost", ""), attributes.getAttribute("email.user", ""),
            attributes.getAttribute("email.passwd", ""), Boolean.parseBoolean(attributes.getAttribute("email.auth", "")));
        String[] eamilTo = pushParameter.getEmailAddress().toArray(new String[1]);
        EMail email = new EMail(attributes.getAttribute("email.user", ""), pushParameter.getTitle(), eamilTo);
        email.setContent(pushParameter.getContent());
        mailSender.sendMail(email);
        logger.debug("retry pushmessage task[{}] successed.",this.taskID);
        this._stop();
    }
}
